package com.proxy.autoclick.clicker.thread;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.http.client.HttpClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.proxy.autoclick.clicker.valueobject.KeywordAddress;
import com.proxy.autoclick.ui.layout.MainFrame;

/**
 * Threadpool for management thread.
 *
 */
@Named
public class ClickerThreadPool {
	
	@Inject
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
	
	@Inject
	private MainFrame mainframe;

	/**
	 * Create thread pool, create a couple threads, pass proxy object and submit task to pool.
	 * When all the thread finish the return.
	 * @param myProxyList
	 * @throws InterruptedException 
	 * @throws IllegalStateException 
	 * @throws FileNotFoundException 
	 */
	public void start(HttpClient httpclient) throws Exception {

//		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		
		File file = new File(mainframe.getSelectFilePath());
		Scanner scan = null;
		try {
			scan = new Scanner(file);
			scan.useDelimiter("\r\n");
		} catch (FileNotFoundException e) {
			mainframe.showMessage(e.getMessage());
			e.printStackTrace();
			return;
		}
		List<ClickerThreadPoolTask> list = new ArrayList<ClickerThreadPoolTask>();
		while(true)
		{
			int i = 0;
			while(scan.hasNext())
			{
				i++;
				KeywordAddress keywordAddress = new KeywordAddress(scan.next());
				list.add(new ClickerThreadPoolTask(keywordAddress,httpclient));
				if(i % 5 == 0)
				{
					break;
				}
			}
			if(i == 0)
				break;
			threadPoolTaskExecutor.getThreadPoolExecutor().invokeAll(list);
			list.clear();
		}

	}
	
	
	public void stop()
	{
		// Wait for threads to finish off.
		threadPoolTaskExecutor.shutdown();
		try {
			// Wait for everything to finish.
			while (!threadPoolTaskExecutor.getThreadPoolExecutor().awaitTermination(2, TimeUnit.SECONDS)) {
//				System.out.println("Awaiting completion of threads.");
				Thread.sleep(100);
			}
			System.out.println("finished checking proxy");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}